var privilageMap = new Map();
var orgMap = new Map();
var ognMap = new Map();
let defPsMap = new Map();
let defPsArray = new Array();
let nameArr = new Array(); //上级岗位名
let layer, form, authtree1, authtree2, tree;
let checked, rowsData, isClicked = false;
const storageValue = "orgPostTableWidths";

layui.config({
    base: '/static/lib/layuiadmin/',
}).extend({
    authtree: 'modules/authtree',
    authtree_zimi: 'modules/authtree_zimi',
}).use(['layer', 'form', 'authtree', 'authtree_zimi', 'tree', 'table'], function () {
        layer = layui.layer;
        authtree1 = layui.authtree;
        authtree2 = layui.authtree_zimi;
        table = layui.table;

        loadOrg(); //加载机构树
    }
);

/*
* 读取机构数据
* */
function loadOrg() {
    $.ajax({
        async: false,
        type: 'post',
        dataType: "json",
        url: '/sys-org/orgList',
        data: {},
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        timeout: 30000,//超时时间设置为1分钟；
        success: function (data) {
            if (data.code == 0) {
                orgMap.clear();

                for (var i = 0; i < data.List.length; i++) {
                    orgMap.set(data.List[i].orgId, data.List[i]);
                }
                renderTree(data);
            } else {
                layer.alert(data.msg, {title: '错误信息：'});
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
        },
        error: function (a, b, c) {
            // 请求出错处理,依然初始化咨询节点信息
            if (b == 'timeout') {
                layer.alert("请求超时，请再次尝试！", {title: '错误信息：'});
            } else {
                layer.alert(url + "请求异常", {title: '错误信息：'});
            }
        }
    });

}

/**
 * 数据封装
 * @param data 数据
 * @param pid  父ID
 * @param id  ID
 * @param name 显示名称
 */

function formatOrgData(values) {
    var tree = []
        , item
        , org;

    // 清空全局变量
    orgMap.clear();

    if (values) {
        var map = new Map();

        // 1)变格式保存到Map
        for (var i = 0; i < values.List.length; i++) {
            item = new Object();

            item.name = values.List[i].orgName;
            item.value = JSON.stringify(values.List[i]).replace(/\"/g, "'");
            // item.spread = true;

            item.list = [];

            // 全局变量赋值
            if (values.List[i].flag == 2) {
                orgMap.set(values.List[i].orgId, item);
            } else {
                map.set(values.List[i].orgId, item);
                tree.push(item);
            }
        }

        // 2)作为子项目加到父项目的list
        for (let key of orgMap) {
            org = JSON.parse(key[1].value.replace(/'/g, "\""));

            // 判断单位还是部门
            if (org.parentId == 0) {
                item = map.get(org.orgCateId);
            } else {
                item = orgMap.get(org.parentId);
            }

            if (item) {
                item.list.push(key[1]);
            }
        }

        // 3)删除没有子项目的list
        removeList(tree, 0);
    }

    return tree;
}

function removeList(list, level) {
    for (var i = list.length - 1; i >= 0; i--) {
        if (list[i].list && list[i].list.length == 0) {
            delete list[i].list;

            if (level == 0) {
                list.splice(i, 1);
            }
        } else {
            removeList(list[i].list, level + 1);
        }
    }
}

function renderTree(data) {
    let trees = formatOrgData(data);

    authtree2.render('#orgTree', trees, {
        inputname: 'authids[]',
        layfilter: 'lay-check-auth',
        autowidth: true,
        // checkType: 'radio',
        // fgo: 0,
        // flags: [1,2]
    });

    //调整机构树中radio框的样式
    // $('span input[type=radio]').parent().parent().css('height','30px');

    //树点击事件
    $('span .layui-icon').on('click', (e) => {
        let ele = $(e)[0].currentTarget.outerHTML;
        let value = $(ele).attr('value');
        let node = eval("("+value+")");
        $(".postText").html(`<span style="color: #F72E29">${node.orgName}</span>有以下岗位`);
        $(".funText").text("");
        $("#functionTree").html('');
        $('#supForm').hide(); //隐藏supForm模块
        renderPostTable(node);
    });

   /* authtree2.on('change(lay-check-auth)', function (data) {
        let checked = authtree2.getChecked('#orgTree'); //获取最新选中
        let node = eval("("+checked+")");
        $(".postText").html(`<span style="color: #F72E29">${node.orgName}</span>有以下岗位`);
        $(".funText").text("");
        $("#functionTree").html('');
        $('#supForm').hide(); //隐藏supForm模块
        renderPostTable(node);
    });*/

    // 树要显示两层
    authtree2.showDept('#orgTree', 2);
}

function renderPostTable(nodeValue) {
    var value = nodeValue;

    var orgIds = getChildOrgs([value.orgId], value.flag);

    if (value.flag == 2) {
        orgIds.push(value.orgId);
    }

    var widths = localStorage[storageValue] ? JSON.parse(localStorage[storageValue]) : [100, 150];

    table.render({
        id: 'sysPostLoad'
        , elem: '#test'
        , url: '/sys-post/postList'
        , method: 'post'
        , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
        , even: true//隔行变色
        , limits: [10, 20, 30, 50, 80, 100]//每页条数的选择项，默认：[10,20,30,50,80,100]。
        , limit: 10//每页显示的条数（默认：10）
        , height: 650
        , request: {}
        , where: {'orgIds': JSON.stringify(orgIds)}
        , cols: [[
            {field: 'id', width: widths[0], title: 'ID', sort: true, align: 'center'}
            , {field: 'name', title: '岗位名称', align: 'left'}
        ]]
        , page: true
    });

    //监听行工具事件
    table.on('tool(upPost)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            , layEvent = obj.event; //获得 lay-event 对应的值
        if (layEvent === 'del') {
            $.ajax({
                url: '/sys-post-superiors/save',
                type: 'post',
                data: {
                    'id': data.id,
                    'originOrgId': data.originOrgId,
                    'postId': data.postId,
                    'state': 2,
                    'orgId': data.orgId,
                    'superiorsId': data.superiorsId,
                    'updateTime': data.updateTime
                },
                success: res => {
                    if (res.code == 0) {
                        layer.msg("删除成功！", {icon: 1});
                    } else {
                        layer.msg(res.msg, {icon: 5});
                    }
                },
                error: () => {
                    layer.msg("请求失败！", {icon: 5});
                },
                complete: () => {
                    let obj = {
                        orgId: data.originOrgId,
                        id: data.postId
                    };
                    loadSuperTable(obj);
                }
            });
        } else if (layEvent === 'up') {
            $.ajax({
                url: '/sys-post-superiors/moveUp',
                type: 'post',
                data: data,
                success: res => {
                    if (res.code == 0) {
                        layer.msg("上移成功！", {icon: 1, time: 1000});
                    } else {
                        layer.msg(res.msg, {icon: 4, time: 1000});
                    }
                },
                error: () => {
                    layer.msg("请求失败！", {icon: 5});
                },
                complete: () => {
                    let obj = {
                        orgId: data.originOrgId,
                        id: data.postId
                    };
                    loadSuperTable(obj);
                }
            });
        } else if (layEvent === 'down') {
            $.ajax({
                url: '/sys-post-superiors/moveDown',
                type: 'post',
                data: data,
                success: res => {
                    if (res.code == 0) {
                        layer.msg("下移成功！", {icon: 1, time: 1000});
                    } else {
                        layer.msg(res.msg, {icon: 4, time: 1000});
                    }
                },
                error: () => {
                    layer.msg("请求失败！", {icon: 5});
                },
                complete: () => {
                    let obj = {
                        orgId: data.originOrgId,
                        id: data.postId
                    };
                    loadSuperTable(obj);
                }
            });
        }
    });

    //监听行单击事件（单击事件为：rowDouble）
    table.on('row(test)', function (obj) {

        $(".funText").html(`给<span style="color: #F72E29">${obj.data.name}</span>授权以下功能`);
        $('#postName').html(`<span style="color: red">${obj.data.name}</span>`);

        load_function_tree(obj.data.id, obj.data.orgId);

        $('#supForm').show(); //显示supForm模块

        rowsData = obj.data;//添加上级岗位

        loadSuperTable(obj.data); //加载上级岗位表格

    });

    $('th').mouseup(function () {
        var tr = $(this).parent()["0"];
        var widths = [];
        for (var i = 0; i < tr.cells.length - 1; i++) {
            widths.push(tr.cells[i].clientWidth);
        }

        localStorage[storageValue] = JSON.stringify(widths);
    });
}

/*
* @author: wj
* @description: 加载授权功能
* @date: 2019/1/17 16:25
* @param
* @return
*/
function load_function_tree(postId, orgId) {
    // 取得岗位授权
    ActHttpRequest('/sys-post-privilege/postFunctionList', {
        'postId': postId,
        'orgId': orgId
    }, function (returnData) {
        if (returnData.code === 0) {
            // 全局变量赋值
            privilageMap.clear();

            if (returnData.List.length > 0) {
                for (var i = 0; i < returnData.List.length; i++) {
                    privilageMap.set(returnData.List[i].functionId, returnData.List[i]);
                }
            }

            var values = formatFunctionData(returnData, "parentId", "functionId", "name", "choiceFlag");
            authtree1.render('#functionTree', values, {
                inputname: 'authids[]'
                , layfilter: 'lay-check-auth2'
                , autowidth: true
                , autochecked: false
                , autoclose: false
                , flag: [1, 3, 4]
            });
        }
    });

    authtree1.on('change(lay-check-auth2)', function (data) {
        var lastChecked = authtree1.getLastChecked('#functionTree') //获取最新选中
            , lastNotChecked = authtree1.getLastNotChecked('#functionTree') // 获取最新取消
            , value // 保存值的变量
            , parents // 保存父值的变量
            , url;  // 请求URL

        if (lastChecked.length > 0) {
            value = parseInt(lastChecked["0"]);
            parents = getParents([value]);
            url = "/sys-post-privilege/saveFunctionPost";
        } else {
            value = parseInt(lastNotChecked["0"]);
            url = "/sys-post-privilege/deleteFunctionPost";
        }

        // 取得关联子项目编号一栏，并取得实体
        var relationIds = getChilds([value]);
        if (parents && parents.length > 0) {
            relationIds = relationIds.concat(parents);
        }
        relationIds.push(value);
        values = [];
        for (var i = 0; i < relationIds.length; i++) {
            var tmpPrivilege = privilageMap.get(relationIds[i]);

            if (tmpPrivilege) {
                tmpPrivilege.postId = postId;
                tmpPrivilege.orgId = orgId;
                values.push(tmpPrivilege);
            }
        }

        // 向服务器发出Ajax请求
        $.ajax({
            async: false,
            type: 'post',
            dataType: "json",
            url: url,
            data: {"privilageList": JSON.stringify(values)},
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            timeout: 30000,//超时时间设置为1分钟；
            success: function (data) {
                if (data.code == 0) {
                    layer.msg("提交成功!", {icon: 1, time: 1000});
                } else {
                    layer.msg(data.msg, {icon: 1, time: 1000});
                }
            },
            complete: function (XMLHttpRequest, textStatus) {
                load_function_tree(postId, orgId);
            },
            error: function (a, b, c) {
                // 请求出错处理,依然初始化咨询节点信息
                if (b == 'timeout') {
                    layer.alert("请求超时，请再次尝试！", {title: '错误信息：'});
                } else {
                    layer.alert(url + "请求异常", {title: '错误信息：'});
                }
            }
        });
    });
}

/**
 * 数据封装
 * @param data 数据
 * @param pid  父ID
 * @param id  ID
 * @param name 显示名称
 * @param checked 选中状态
 */
function formatFunctionData(values, pid, id, name, checked) {
    var tree = [],
        item;

    var map = new Map();

    // 1)变格式保存到Map
    for (var i = 0; i < values.List.length; i++) {
        item = new Object();

        item.name = values.List[i][name];
        item.value = values.List[i][id];
        item.checked = values.List[i][checked];
        item.list = [];

        map.set(values.List[i][id], item);
    }

    // 2)作为子项目加到父项目的list
    for (var i = 0; i < values.List.length; i++) {
        if (values.List[i][pid] > 0) {
            var obj = map.get(values.List[i][pid]);
            obj.list.push(map.get(values.List[i][id]));
        } else {
            tree.push(map.get(values.List[i][id]));
        }
    }

    // 3)删除没有子项目的list
    for (var i = 0; i < values.List.length; i++) {
        var obj = map.get(values.List[i][id]);
        if (obj.list.length == 0) {
            delete obj.list;
        }
    }

    return tree;
}

/**
 * 取得授权功能子节点Id一览
 */
function getChilds(ids) {
    var result = [];

    for (value of privilageMap) {
        if (ids.indexOf(value[1].parentId) >= 0) {
            result.push(value[1].functionId);
        }
    }

    if (result.length > 0) {
        result = result.concat(getChilds(result));
    }

    return result;
}

/**
 * 取得授权功能父节点Id一览
 */
function getParents(ids) {
    var result = [];

    var obj = privilageMap.get(ids[ids.length - 1]);
    var parent;

    // 查找上一个父节点，若没选中的状态则加到result
    if (obj.parentId > 0) {
        parent = privilageMap.get(obj.parentId);
        if (!parent.choiceFlag) {
            result.push(obj.parentId);
            result = result.concat(getParents(result));
        }
    }

    return result;
}

/**
 * 取得机构子节点Id一览
 */
function getChildOrgs(ids, flag) {
    let result = [];
    let obj;

    for (value of orgMap) {
        obj = JSON.parse(value[1].value.replace(/'/g, "\""));

        if (flag == 1) {
            if (ids.indexOf(obj.orgCateId) >= 0) {
                result.push(obj.orgId);
            }
        } else {
            if (ids.indexOf(obj.parentId) >= 0) {
                result.push(obj.orgId);
            }
        }
    }

    if (result.length > 0) {
        result = result.concat(getChildOrgs(result, 2));
    }

    return result;
}

/**
 * @author wh
 * @desc 加载上级岗位表格
 */
function loadSuperTable(data) {

    table.render({
        elem: '#upPost'
        , height: 275
        , url: '/sys-post-superiors/getCurRowChecked' //数据接口
        , title: '上级岗位表'
        , even: true//隔行变色
        , limit: 5
        , limits: [5, 10, 15, 20, 25, 30, 35, 40]
        , where: {
            'originOrgId': data.orgId,
            'postId': data.id
        }
        , page: true //开启分页
        , cols: [[ //表头
            {field: 'orgName', title: '机构名'}
            , {field: 'superiorsName', title: '上级岗位名'}
            , {fixed: 'right', title: '操作', align: 'center', toolbar: '#barDemo'}
        ]]
    });
}


/**
 * @author wh
 * @desc 选择上级领导
 */
$('#SuperiorPost').on('click', function () {

    let index = layer.open({
        type: 1,
        title: '加载上级岗位',
        btn: ['确定', '取消'],
        area: ['600px', '500px'],
        shade: 0, //关闭遮罩
        content: $('#loadPostTree'),
        success: function () {
            $.ajax({
                url: '/sys-post-privilege/getSupPostList',
                type: 'post',
                // async: false,
                data: {
                    'orgId': rowsData.orgId,
                    'postId': rowsData.id
                },
                dataType: 'json',
                success: function (res) {
                    if (res.code == 0) {
                        let unCheckedArr = [];
                        let result = [];
                        //1 过滤得到state为1的数据
                        if (res.supData.length > 0) {
                            result = res.supData.filter(item => (item.state === 1));
                            // 2 过滤出默认岗位
                            let Array = res.supData.filter(item => (item.superiorsId == 0));

                            //3 事先备用好上级岗位表中已有的数据，然后到树结构中加入其id和updateTime
                            if (Array.length > 0) {
                                Array.forEach(item => {
                                    defPsMap.set(item.orgId, item);
                                    defPsArray.push(item.orgId);
                                });
                            }
                        }

                        if (result && result.length > 0) {
                            unCheckedArr = result.map(item => `${item.orgId}-${item.superiorsId}`);
                        }
                        var trees = formatData1(res.data, 'parentId', 'id', 'name', 'choiceFlag');

                        // 如果后台返回的不是树结构，请使用 authtree.listConvert 转换
                        authtree2.render('#postTree', trees, {
                            inputname: 'authids[]',
                            layfilter: 'lay-check-auth',
                            autowidth: true,
                            checkType: 'radio',
                            uncheckedArr: unCheckedArr,
                            fgo: 2,
                            flags: [3]
                        });

                        // 点击机构节点事件
                        $('span[state="2"]').on('click', function (res) {
                            let aaa = $("input[type=\"radio\"]").prop("checked", false);
                            form.render("radio");

                            let div_auth_status = $(this).parent().parent().parent();
                            let div_child_single = div_auth_status.next("div.auth-child").children("div.auth-single").children("div").children("div.auth-status").children("span").children("span").children("input[type=\"radio\"]");
                            let checkBox, checkValue;

                            if (div_child_single && div_child_single.length > 0){
                                checkBox = div_child_single[div_child_single.length - 1];

                                checkValue = JSON.parse(checkBox.defaultValue.replace(/'/g, "\""));

                                if (checkValue.postId == 0) {
                                    checkBox.checked = true;

                                    form.render("radio");
                                }
                            }

                            let currentValue = JSON.parse($(this).attr('value').replace(/'/g, "\""));

                            let obj = ognMap.get(currentValue.ognId);

                            // 点击时岗位为默认岗位
                            postObj = JSON.stringify({
                                orgId: currentValue.id
                                ,parentId: currentValue.id
                                ,orgName: currentValue.orgName
                                ,postName: obj.postName
                                ,superiorsId: null
                                ,updateTime: null
                                ,id:0
                                ,postId:0
                                ,flag:3
                            });

                            checked = postObj;
                            isClicked = true; //表示树已经是点击状态
                        });

                        authtree2.on('change(lay-check-auth)', function (data) {
                            // 获取已选中节点
                            isClicked = true; //表示树已经是点击状态
                            checked = authtree2.getChecked('#postTree');
                        });

                        authtree2.showDept('#postTree', 2);

                    } else {
                        layer.msg(res.msg, {icon: 5});
                    }
                }
            });
        },
        yes: function () {

            if (isClicked && checked && checked.length > 0) {

                let obj = eval("(" + checked + ")");
                //向上级岗位表里保存选中岗位
                $.ajax({
                    url: '/sys-post-superiors/save',
                    type: 'post',
                    data: {
                        'id': obj.superiorsId,
                        'originOrgId': rowsData.orgId,
                        'postId': rowsData.id,
                        'state': 1,
                        'orgId': obj.orgId,
                        'superiorsId': obj.postId,
                        'updateTime': obj.updateTime
                    },
                    success: res => {
                        if (res.code == 0) {
                            layer.msg("保存成功！", {icon: 1, time: 1000});
                        } else {
                            layer.msg(res.msg, {icon: 5, time: 2000});
                        }
                    },
                    error: () => {
                        layer.msg("请求失败！", {icon: 5, time: 2000});
                    },
                    complete: () => {
                        loadSuperTable(rowsData);
                    }

                });
            }

            layer.close(index);
        },
        btn2: function () {

        },
        end: function () {
           isClicked = false;
        }
    });
});

/**
 * 数据封装
 * @param data 数据
 * @param pid  父ID
 * @param id  ID
 * @param name 显示名称
 * @param checked 选中状态
 */
function formatData1(values, pid, id, name, checked) {
    var tree = [],
        item,
        obj,
        tmpObj,
        ognObj;

    // 全局变量赋值
    orgMap.clear();
    ognMap.clear();

    let postMap = new Map();
    let orgList = [];
    let cateMap = new Map();

    // 1)变格式保存到Map
    for (var i = 0; i < values.length; i++) {
        item = new Object();

        item.name = values[i][name];
        item.value = JSON.stringify(values[i]).replace(/"/g, "'");
        item.checked = values[i][checked];
        item.list = [];

        switch (values[i].flag) {
            case 1:
                item.name = values[i].orgName;
                cateMap.set(values[i].orgId, item);
                tree.push(item);
                break;
            case 2:
                orgMap.set(values[i][id], item);
                orgList.push(values[i]);

                if (values[i][pid] == 0) {
                    ognMap.set(values[i][id], values[i]);
                }

                break;
            case 3:
                postMap.set(values[i][id], item);
                break;
        }
    }

    // 2)插入默认岗位
    // 2.1) 在已有的表中把默认岗位的id和updateTIme加入进去
    if (orgList.length > 0) {
        orgList.map(item => {
            if (defPsArray.indexOf(item.orgId) > -1) {
                item.superiorsId = defPsMap.get(item.orgId).id;
                item.updateTime = defPsMap.get(item.orgId).updateTime;
            }
        });
    }

    for (var i = 0; i < orgList.length; i++) { // 遍历Array
        obj = orgMap.get(orgList[i][id]);
        ognObj = JSON.parse(obj.value.replace(/'/g, "\""));

        if (!orgList[i].roleId) continue;

        tmpObj = new Object();
        tmpObj.orgId = orgList[i][id];
        tmpObj.parentId = orgList[i][id];
        tmpObj.orgName = ognObj.orgName;
        tmpObj.superiorsId = orgList[i].superiorsId; //加入数据表中已有默认岗位的id和时间
        tmpObj.updateTime = orgList[i].updateTime;

        ognObj = ognMap.get(orgList[i].ognId);
        tmpObj.postName = ognObj.postName;

        tmpObj.id = 0;
        tmpObj.postId = 0;
        tmpObj.flag = 3;

        item = new Object();
        item.name = tmpObj.postName;
        item.value = JSON.stringify(tmpObj).replace(/"/g, "'");
        item.checked = false;
        item.list = [];

        obj.list.push(item);
    }

    // 3)作为子项目加到父项目的list
    for (var i = 0; i < values.length; i++) {

        switch (values[i].flag) {
            case 1:
                break;
            case 2:
                if (values[i][pid] > 0) {
                    obj = orgMap.get(values[i][pid]);
                    obj.list.push(orgMap.get(values[i][id]));
                } else {
                    obj = cateMap.get(values[i].orgCateId);
                    obj.list.push(orgMap.get(values[i][id]));
                }

                break;
            case 3:
                obj = orgMap.get(values[i].orgId);

                if (obj.list.length > 0) {
                    obj.list.splice(obj.list.length - 1, 0, postMap.get(values[i][id]));
                } else {
                    obj.list.push(postMap.get(values[i][id]));
                }

                break;
        }
    }

    // 4)删除没有子项目的list
    removeList(tree, 0);

    return tree;
}


function removeList(list, level) {
    for (var i = list.length - 1; i >= 0; i--) {
        if (list[i].list && list[i].list.length == 0) {
            delete list[i].list;

            if (level == 0) {
                list.splice(i, 1);
            }
        } else {
            removeList(list[i].list, level + 1);
        }
    }
}

